#!/bin/sh

echo "Build Output: /tmp/link_test"
[ -d /tmp/link_test ] || mkdir -p /tmp/link_test

set -x
gcc -c b.c -o /tmp/b.o
ar rs /tmp/link_test/libb.a /tmp/b.o

gcc -shared bs.c -o /tmp/link_test/libbs.so

gcc -c -L/tmp/link_test a.c  -lb -lbs  -o /tmp/a.o 
ar rs /tmp/link_test/liba.a /tmp/a.o


#error: 未连接静态库自身的依赖
gcc -shared -L/tmp/link_test -Wl,-rpath,\$ORIGIN s.c -la -o /tmp/link_test/libs1.so 
#ERROR: s1引用未定义符号
gcc -L/tmp/link_test -Wl,-rpath,\$ORIGIN main.c -ls1 -o /tmp/link_test/ltest

#error: 链接顺序
gcc -shared -L/tmp/link_test -Wl,-rpath,\$ORIGIN s.c -lbs -lb -la  -o /tmp/link_test/libs2.so 
#ERROR: s2引用未定义符号
gcc -L/tmp/link_test -Wl,-rpath,\$ORIGIN main.c -ls2 -o /tmp/link_test/ltest

gcc -shared -Wl,-rpath,\$ORIGIN -L/tmp/link_test s.c -la -lb -lbs -o /tmp/link_test/libs.so  
gcc -L/tmp/link_test -Wl,-rpath,\$ORIGIN main.c -ls -o /tmp/link_test/ltest

nm --defined-only  /tmp/link_test/*.so /tmp/link_test/*.a |awk '{if($2 == "T") { print "\t"$2,$3 }  if($1 ~ ".*\.so:" || $1 ~ ".*\.a:") print  }' 2>/dev/null
readelf -d /tmp/link_test/ltest /tmp/link_test/*.so |awk '{if($1=="File:") {print $2} if($2 == "(NEEDED)" || $2 == "(RUNPATH)" ) {print "\t"$3$4$5} }'
